#!/bin/bash
set -euo pipefail

err() {
    echo "$@" >&2
}

fatal() {
    err "$@"
    exit 1
}

if [ $# -eq 0 ]; then
    err "Usage: $0 [PATTERN...]"
    err " e.g.: $0 /etc/passwd '/etc/group*'"
fi

if [ ! -f /sysroot/etc/selinux/config ]; then
    exit 0
fi

source /sysroot/etc/selinux/config

if [ -z "${SELINUXTYPE:-}" ]; then
    fatal "Couldn't find SELINUXTYPE in /sysroot/etc/selinux/config"
fi

file_contexts="/sysroot/etc/selinux/${SELINUXTYPE}/contexts/files/file_contexts"

# feature detection until RHEL8 kernel has
# https://lore.kernel.org/selinux/20190912133007.27545-1-jlebon@redhat.com/T/#m5f950ca9fc3ed374cb793fc9aed0435602b1b6ad
can_setfiles() {
    CAN_SETFILES_STAMP=/run/.coreos-relabel-can-setfiles
    if [ ! -f ${CAN_SETFILES_STAMP} ]; then
        touch /sysroot/etc/.setfiles-test
        trap 'rm /sysroot/etc/.setfiles-test' EXIT
        if setfiles -Fr /sysroot "$file_contexts" /sysroot/etc/.setfiles-test &>/dev/null; then
            echo 1 > ${CAN_SETFILES_STAMP}
        else
            echo 0 > ${CAN_SETFILES_STAMP}
        fi
    fi
    grep -q 1 ${CAN_SETFILES_STAMP}
}

if can_setfiles; then
    prefixed_patterns=()
    while [ $# -ne 0 ]; do
        pattern=$1; shift
        prefixed_patterns+=("/sysroot/$pattern")
    done
    setfiles -vFi0 -r /sysroot "$file_contexts" "${prefixed_patterns[@]}"
else
    while [ $# -ne 0 ]; do
        pattern=$1; shift
        # Really, we could handle /etc files here earlier by spitting out a
        # separate unit service like ignition-relabel.service was. But let's not
        # do that until the need arises.
        echo "Z $pattern - - -" >> /run/tmpfiles.d/var-relabel.conf
    done
fi
